package check

import (
	"io/fs"
	"net/http"
	"operator/scripts"
	"operator/utils/logs"
	"os"
	"path/filepath"

	"github.com/gin-gonic/gin"
)

func init() {
	tmpDir := "/tmp/operator-scripts"
	os.MkdirAll(tmpDir, 0755)

	logs.Info(nil, "init shell scripts")
	fs.WalkDir(scripts.Scripts, ".", func(path string, d fs.DirEntry, err error) error {
		if err != nil || d.IsDir() {
			return err
		}

		content, err := scripts.Scripts.ReadFile(path)
		if err != nil {
			return err
		}

		targetPath := filepath.Join(tmpDir, filepath.Base(path))
		return os.WriteFile(targetPath, content, 0755)
	})
}

func CheckBackup(c *gin.Context) {
	scriptPath := "/tmp/operator-scripts/backup.sh"
	out, err := scripts.RunShell(scriptPath)
	if err != nil {
		logs.Error(map[string]interface{}{"error": err.Error()}, "备份检查异常")
		c.String(http.StatusInternalServerError, out)
		return
	}
	logs.Info(nil, "备份检查成功")
	c.String(http.StatusOK, out)
}
